<template>
  <div class="limit-info">
    <el-form ref="form" :model="model" label-width="170px" class="top-search-box">
      <el-row :gutter="20">
        <el-col :span="8">
            <el-form-item label="组织名称" prop="enterpriseName" :rules="[{ required: true, message: '请输入工商注册名', trigger: 'blur' }]">
                <el-input maxlength="200" v-model="model.enterpriseName" placeholder="请输入" clearable></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="组织类型" prop="enterpriseType" :rules="[{ required: true, message: '请选择组织类型', trigger: 'blur' }]">
            <el-select v-model="model.enterpriseType" clearable>
              <el-option v-for="item in organizeList" :key="item.primaryKey" :label="item.name" :value="item.primaryKey" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label="统一社会信用代码" prop="businessLicenseNo" :rules="[{ required: true, message: '请输入统一社会信用代码', trigger: '' }]">
                <el-input maxlength="200" v-model="model.businessLicenseNo" placeholder="请输入" clearable></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="24">
            <el-form-item label="说明">
                <el-input  type="textarea" autosize :rows="3" maxlength='200' v-model="model.enterpriseDesc" placeholder="请输入" clearable></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label="状态" prop="status" :rules="[{ required: true, message: '请选择企业状态', trigger: '' }]">
              <el-select v-model="model.status" clearable>
                <el-option v-for="item in statusList" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label="管理员" prop="enterpriseManager" :rules="[{ required: true, message: '请输入管理员', trigger: 'blur' }]">
                <el-input maxlength="200" v-model="model.enterpriseManager" placeholder="请输入" clearable></el-input>
            </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label="电子邮箱" prop="enterpriseEmail" :rules="[{ required: true, message: '请输入电子邮箱', trigger: 'blur' },,{ pattern: /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,message: '请输入正确电子邮箱',trigger: 'blur'}]">
                <el-input maxlength="200" :readonly="model.mailIfVerify ? true : false" v-model="model.enterpriseEmail" placeholder="请输入">
                    <el-button v-if="$route.query.key && !model.mailIfVerify" slot="append" type="text" @click="verifyEmail">验证</el-button>
                    <el-button v-if="$route.query.key && model.mailIfVerify" slot="append" type="text" disabled>已验证</el-button>
                </el-input>
            </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-form-item label="手机号码" prop="enterpriseManagerPhone" :rules="[{ required: true, message: '请输入手机号码', trigger: 'blur' },{ pattern: /^1\d{10}$/,message: '请输入正确手机号',trigger: 'blur'}]">
                <el-input maxlength="11" :readonly="model.phoneIfVerify ? true : false" v-model.number="model.enterpriseManagerPhone" placeholder="请输入">
                    <el-button v-if="$route.query.key && !model.phoneIfVerify" slot="append" type="text" @click="verifySms">验证</el-button>
                    <el-button v-if="$route.query.key && model.phoneIfVerify" slot="append" type="text" disabled>已验证</el-button>
                </el-input>
            </el-form-item>
        </el-col>
    
        <el-col :span="8">
          <el-form-item label="授权函" prop="authLetter"  :rules="[{ required: true, message: '请上传授权函', trigger: '' }]">
            <UploadAlbum :height="200" :width="198" v-bind:file-key.sync="model.authLetter" v-bind:cover-url.sync="model.authLetterUrl"></UploadAlbum>
          </el-form-item>
        </el-col>
        <el-col :span="24">
            <!-- <el-button v-if="false" size="small" type="primary" @click="()=>{qiChachaDialog=true}" class="default-button f-right m-r-m">企查查查询</el-button> -->
            <el-button v-if="model.status != 1 && model.status != 0" size="small" type="danger" @click="deleteFirm()" class="default-button f-right m-r-m">删除</el-button>
            <el-button v-if="model.status == 3 || model.status == 5" size="small" type="success" @click="save(1)" class="default-button f-right m-r-m">开通</el-button>
            <el-button size="small" type="primary" @click="save('')" class="default-button f-right m-r-m">保存</el-button>
            <el-button v-if="model.status == 1" size="small" type="primary" @click="save(3)" class="default-button f-right m-r-m">关闭</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 企查查 -->
    <el-dialog title="企业信息" :visible.sync="qiChachaDialog" width="60%" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="()=>{qiChachaDialog=false}">
        <el-form :model="model" label-width="170px" class="top-search-box" >
          <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="businessLicenseNo" disabled >
                  <el-input maxlength="200" v-model="model.businessLicenseNo"></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="工商注册名" prop="enterpriseName" disabled>
                  <el-input maxlength="200" v-model="model.enterpriseName"></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="法定代表人" prop="corporateRep" disabled>
                  <el-input maxlength="200" v-model="model.corporateRep" ></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="成立日期" prop="setUpDate" disabled>
                <el-date-picker v-model="model.setUpDate" type="date" value-format="timestamp" ></el-date-picker>
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="企业状态" prop="status" disabled>
                  <el-input v-model="model.status"></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="注册号" prop="registerNo" disabled>
                  <el-input maxlength="200" v-model="model.registerNo"></el-input>
              </el-form-item>
          </el-col>
        </el-form>
    </el-dialog>
  </div>
</template>
<script>
import * as Port from "../../../api";
import { formValid } from '@/lib/utils'
import merge from 'webpack-merge';
import {requestTips,askDialog} from "../../../assets/util"
export default {
  data() {
    return {
      model: {
        enterpriseType: '',
        enterpriseName: '',
        setUpDate: '',
        status: '',
        registerNo: '',
        businessLicenseNo: '',
        enterpriseManager: '',
        enterpriseManagerPhone: '',
        enterpriseEmail: '',
        enterpriseDesc: '',
        authLetter: '',
        authLetterUrl: '',
      },
      statusList:[
        {value:0,name:'已删除'},
        {value:1,name:'已开通'},
        {value:3,name:'已关闭'},
        {value:5,name:'草稿'},
      ],
      organizeList:[
        {primaryKey:'1',name:"企业"},
        {primaryKey:'2',name:"团队"}
      ],
      businessList:[
        {primaryKey:'1',name:"商务写字楼"},
        {primaryKey:'2',name:"公寓"},
        {primaryKey:'3',name:"物业"}
      ],
      qiChachaDialog:false,
      codeModel:{
        yanzhengma:""
      },
      enterpriseStatus: null
    };
  },
  watch:{
    // 'model.enterpriseName': {
    //   handler(newVal,oldVal) {
    //     if(newVal && newVal!=oldVal && false){
    //       this.qiChacha()
    //     }
    //   },
    //   immediate: true,
    //   deep: true,
    // },
  },
  created() {
    // 获取默认的企业key
    if (!this.$route.query.key && localStorage.getItem('userEnterpriseid') && this.$route.query.isAdd != 1) {
      this.$route.query.key = localStorage.getItem('userEnterpriseid')
    }
  },

  computed: {
    rightPhone() {
      return /^1\d{10}$/.test(this.model.enterpriseManagerPhone)
    },
    rightEmail() {
      return /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/.test(this.model.enterpriseEmail)
    }
  },

  mounted() {
    this.getInfo()
  },

  methods: {
    
    //数据源
    async getInfo() {
      if (this.$route.query.key) {
        let res = await Port.apiEnterpriseInfo(this.$route.query.key)
        this.model = res
      }
    },
    //保存
    save(type) {
      this.enterpriseStatus = type
      formValid(this, 'form', this.saveFn)
      // this.saveFn(type)
    },
    async saveFn(type){
      let param = JSON.parse(JSON.stringify(this.model))
      param.status = this.enterpriseStatus ? this.enterpriseStatus : null
      param.primaryKey = param.key ? param.key : null
      let res = this.$route.query.key ? await Port.apiEnterpriseEdit(param) : await Port.apiEnterpriseAdd(param)
      requestTips(res,() => {
        if (this.$route.query.key) {
          this.getInfo()
        } else {
          this.$router.replace({
            query: merge(this.$route.query, { key: res.key, isAdd: 0 })
        });
        }
      })
    },
    //验证手机号
    async verifySms(){
      await Port.sendValidateSms({
        enterpriseid:this.$route.query.enterpriseid,
        validateValue:this.model.enterpriseManagerPhone
      })
      this.$message.success('短信已发送，请注意查收！')
    },
    //验证邮箱
    async verifyEmail () {
      if (!this.rightEmail) {
        this.$message.error('请输入正确的邮箱');
        return
      }
      await Port.apiVerifyEmail({
        enterpriseid:this.$route.query.enterpriseid,
        validateValue:this.model.enterpriseEmail,
        domain:window.location.origin
      })
      this.$message.success('邮件已发送，请注意查收！')
    },
     //删除
    deleteFirm (item) {
      askDialog("是否删除该组织？",async () => {
          const res = await Port.apiEnterpriseDel(this.$route.query.key)
          requestTips(res,()=>{
          })
      })
    },
    //企查查
    async qiChacha () {
      let res = await Port.apiQiChacha({
        keyword:this.model.enterpriseName
      })
      if (res.result && res.result.length > 0) {
        let item = res.result[0]
        this.model.corporateRep = item.operName
        this.model.setUpDate = item.startDate
        this.model.status = item.status
        this.model.registerNo = item.no
        this.model.businessLicenseNo = item.creditCode
      }
    },
 
  }
};
</script>
<style lang="scss" scoped>
.el-button+.el-button {
    margin-left: 0!important;
}
.limit-info{
    .top-search-box{
        padding: 16px;
    }
    ::v-deep .flex-col-item{
        .el-form-item__content{
            display: flex;
        }
    }
    ::v-deep .el-input-group__append{
        border: none;
    }
    ::v-deep .el-form-item__content .el-input-group {
        vertical-align: inherit;
    }
}
</style>